mui.init({});

mui(document).on('tap', '[data-href]', function () {
    var $url = this.getAttribute("data-href");
    if ($url.length > 0) {
        mui.openWindow({
            id: $url,
            url: $url
        });
    }
});

mui(document).on('tap', '.btn-more', function () {

    if (!$(this).hasClass("on")) {
        $(this).addClass("on");
        $(".con-more").addClass("on");
    } else {
        $(this).removeClass("on");
        $(".con-more").removeClass("on");
    }
});

mui(document).on('tap', '.date_time, .datetime', function () {
    var $this = $(this);
    var dtPicker = new mui.DtPicker({
        "type": "datetime"
    });
    dtPicker.show(function (selectItems) {
        $this.val(selectItems.value);
    })
});

mui(document).on('tap', '.province, .city', function () {
    var $province = $('#activity-province_id');
    var $city = $('#activity-city_id');

    var picker = new mui.PopPicker({
        layer: 2
    });
    picker.setData(window['region']);

    if ($province.length && $province.val().length > 0) {
        picker.pickers[0].setSelectedValue($province.val());
        var items = picker.pickers[0].getSelectedItem();
        var children = items['children'];
        for (var i in children) {
            var item = children[i];
            if (item.value === parseInt($city.val())) {
                picker.pickers[1].setSelectedIndex(i);
                break;
            }
        }
    }

    picker.show(function (SelectedItem) {
        $('.province').val(SelectedItem[0]['text']);
        $('.city').val(SelectedItem[1]['text']);
        if ($province.length) {
            $province.val(SelectedItem[0]['value']);
            $city.val(SelectedItem[1]['value']);
        }
    })
});


mui(document).on('tap', '.company_scale, .industry, .tag', function () {
    var $this = $(this);
    var picker = new mui.PopPicker({layer: 1});

    var company_scale = [
        {value: '0-10人', text: '0-10人'},
        {value: '10-50人', text: '10-50人'},
        {value: '100人以上', text: '100人以上'}
    ];
    var industry = [
        {value: '移动互联网', text: '移动互联网'},
        {value: '电子商务', text: '电子商务'},
        {value: '教育', text: '教育'},
        {value: '其他', text: '其他'}
    ];
    var tag = [
        {value: '大专及以上', text: '大专及以上'},
        {value: '本科', text: '本科'},
        {value: '硕士', text: '硕士'},
        {value: '博士', text: '博士'}
    ];
    var $data = {
        'tag': tag,
        'industry': industry,
        'company_scale': company_scale
    };
    var $class = $this.attr('class').replace('form-control', '');
    $class = $.trim($class);
    picker.setData($data[$class]);


    picker.show(function (SelectedItem) {
        $this.val(SelectedItem[0]['text']);
    })
});


mui(document).on('tap', '.like', function () {
    App.like($(this));
});

mui(document).on('tap', '.apply', function () {
    var $this = $(this);
    if (!App.checkLogin()) {
        return false;
    }

    if ($this.hasClass('disabled')) {
        mui.toast('只有学生可以参与');
        return false;
    }

    App.ajax.get($this, {url: $this.attr('id')}, function (res) {
        if (res['code'] === 0) {
            mui.toast('报名成功');
        } else {
            mui.toast(res['msg']);
        }
    });
});

mui(document).on('tap', '.favorite', function () {
    var $this = $(this);
    if ($this.hasClass('disabled')) {
        mui.toast('只有学生可以收藏');
        return false;
    }

    if ($this.hasClass('light')) {
        mui.toast('已经收藏了');
    }
    if (!App.checkLogin()) {
        return false;
    }

    var $url = $this.attr('id');
    mui.getJSON($url, function (res) {
            if (res['code'] === 0) {
                $this.addClass('light');
            }
        }
    );
});

mui(document).on('tap', '.comment_like', function () {
    var $this = $(this);
    if ($this.hasClass('checked')) {
        return;
    }
    var $url = $this.attr('id');
    mui.getJSON($url, function (res) {
            if (res['code'] === 0) {
                $this.addClass('checked');
                var text = $this.text();
                n = parseInt(text.match(/\d+/));
                $this.text(text.replace(n, n + 1));
            }
        }
    );
});


mui(document).on('tap', '.comments_like', function () {
    var $this = $(this);
    if ($this.hasClass('checked')) {
        return;
    }
    var $url = $this.attr('id');
    mui.getJSON($url, function (res) {
            if (res['code'] === 0) {
                $this.addClass('checked');
                var $span = $this.find('span');
                var text = $span.text();
                n = parseInt(text.match(/\d+/));
                $span.text(text.replace(n, n + 1));
            }
        }
    );
});

mui(document).on("tap", "#commentOpenPopOver", function () {
    if (typeof window['user']['type'] === 'undefined') {
        mui.confirm('请登录后发表评论', '', ['去登录', '取消'], function (e) {
            if (e.index === 0) {
                window.location.href = window['loginUrl'];
            }
        });
        return;
    }
    mui("#commentPopover").popover("show");
});

mui(document).on("tap", ".J-commentOpenPopOver", function () {
    var $this = $(this);
    if (typeof window['user']['type'] === 'undefined') {
        mui.confirm('请登录后发表评论', '', ['去登录', '取消'], function (e) {
            if (e.index === 0) {
                window.location.href = window['loginUrl'];
            }
        });
        return;
    }
    mui("#commentPopover").popover("show");
    $('#comment-parent_id').val($this.attr('id'));
});

mui(document).on("tap", "#shareOpenPopover", function () {
    mui.toast('请点击右上角按钮进行分享', {duration: 'long', type: 'div'});
});

mui(document).on("tap", ".save-avatar", function () {
    var $this = $(this);
    wx.chooseImage({
        count: 1,
        success: function (res) {
            var localIds = res.localIds;
            var len = localIds.length;
            for (var i = 0; i < len; i++) {
                var localId = localIds[i];
                App.upLoadImg(localId, function (res) {
                    $('.user-avatar').attr('src', localId);
                    $.get($this.attr('id'), {'mid': res['serverId']});
                });
            }
        }
    });
    // App.chooseImage(1, function (data) {
    //     //$('.user-avatar').attr('src', localId);
    //     //$.get($this.attr('id'), {'mid': res['serverId']});
    //     console.log(data);
    // })
});

mui(document).on("tap", ".uploader__input", function () {
    var name = $(this).attr('id');
    App.chooseImage(5, null, name);
});


var App = App || {};
App.isJson = function (obj) {
    return typeof(obj) === "object" && Object.prototype.toString.call(obj).toLowerCase() === "[object object]" && !obj.length;
};

App.checkLogin = function () {
    if (typeof window['user']['type'] === 'undefined') {
        mui.confirm('请先登录后在操作', '', ['去登录', '取消'], function (e) {
            if (e.index === 0) {
                window.location.href = window['loginUrl'];
            }
        });
        return false;
    }
    return true;
};

App.upLoadImg = function (localId, callback, name) {
    wx.uploadImage({
        localId: localId,
        isShowProgressTips: 1,
        success: callback || function (res) {
            if (callback) {
                callback(res);
                return;
            }
            var serverId = res.serverId;
            var obj = $('#' + name).parents('.uploader__bd').find('.uploader__files');
            var item = $('<li />', {
                'html': [
                    '<img class="uploader__file" src="' + localId + '">',
                    '<input type="hidden" name="' + name + '[]" value="' + serverId + '">',
                    '<i class="del del-image"></i>'
                ],
                'class': 'uploader__file'
            });
            obj.append(item);
        }
    });
};

App.chooseImage = function (count, callback, name) {
    wx.chooseImage({
        count: count || 3,
        success: function (res) {
            var localIds = res.localIds;
            var len = localIds.length;
            for (var i = 0; i < len; i++) {
                App.upLoadImg(localIds[i], callback, name);
            }
        }
    });
};

App.like = function ($this, callback) {
    if ($this.hasClass('light')) {
        mui.toast('点过赞了。');
        return;
    }
    var $url = $this.attr('id');
    mui.getJSON($url, callback || function (res) {
            if (res['code'] === 0) {
                $this.addClass('light');
            } else {
                mui.toast(res['msg']);
            }
        }
    );
};

App.commentList = function () {
    var $this = $('.comment-list');
    $.get($this.attr('id'), function (html) {
        $this.append(html);
        if (typeof window['pager'] === 'object') {
            App.scrollRefresh('.comment-list', window['pager']['pageCount'], window['pager']['pageUrl']);
        }
    }, 'html');
};

App.scrollRefresh = function (parent, $pageCount, $pageUrl) {
    var counter = 1;
    var isEnd = false;
    var $parent = parent || $('.refresh-list');
    var loadData = function (url) {
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'html',
            success: function (html) {
                window.setTimeout(function () {
                    if (html.length < 10) {
                        isEnd = false;
                        status('done');
                    } else {
                        $($parent).append(html);
                        isEnd = false;
                        status('init');
                    }
                }, 1000);
            }
        });
    };

    var status = function (method) {
        var $container = $('.mui-pull-bottom-pocket');
        if ($container.length <= 0) {
            var html = $('<div class="mui-pull-bottom-pocket mui-block">\
                <div class="mui-pull">\
                <div class="mui-pull-loading mui-icon mui-spinner mui-visibility"></div>\
                <div class="mui-pull-caption mui-pull-caption-refresh">正在加载...</div>\
                </div>\
                </div>');
            html.appendTo($parent);
        }
        if (method === 'show') {
            $container.addClass('mui-visibility');
        } else if (method === 'done') {
            $container.addClass('mui-visibility');
            $('.mui-pull-loading').removeClass('mui-visibility');
            $('.mui-pull-caption').html('没有更多了。');
            window.setTimeout(function () {
                $container.remove();
            }, 3000);
        } else if (method === 'init') {
            $container.remove();
        } else {
            $container.removeClass('mui-visibility');
        }
    };

    $(window).scroll(function () {
        if (isEnd === true) {
            return;
        }

        status('hide');

        if ($(document).height() - $(this).scrollTop() - $(this).height() < 100) {
            counter++;
            if (counter > $pageCount) {
                status('done');
                return;
            }

            status('show');
            isEnd = true;
            var url = $pageUrl.replace('%24page', counter);
            loadData(url);
        }
    });
};

App.ajax = {};
App.ajax.request = function ($this, method, option) {
    var options = $.extend({type: 'json'}, option);
    var text = $this.attr('title') || $this.data('original-title') || $this.val() || $this.text();

    if ($this.hasClass('disabled')) {
        return;
    }

    $this.attr('disabled', 'disabled').fadeTo(0.8).html('正在' + text + '...');

    $.ajax({
        type: method,
        url: options.url || $this.attr('href'),
        data: options.data,
        context: $this,
        beforeSend: function () {
        },
        error: options.error || function (jqXHR, statusText, error) {
            $this.removeAttr('disabled').html(text).fadeTo(1);
        },
        success: options.success || function (result) {
            if (!App.isJson(result)) {
                $('body').append(result);
                return;
            }
            window.setTimeout(function () {
                if (result['code'] === 0) {
                    var redirect = $this.data('redirect') || $this.attr('redirect') || result['redirect'] || result['data']['redirect'] || false;
                    if (redirect) {
                        window.location.href = redirect;
                    } else {
                        window.location.reload();
                    }
                    return;
                }
                mui.alert(result['msg']);
                $this.removeAttr('disabled').html(text).fadeTo(1);
            }, 1700);
        }
    });
};

App.ajax.get = function ($this, options) {
    App.ajax.request($this, 'GET', options);
};

App.ajax.post = function ($this, option) {
    var options = option || {};
    if (!options.data && !options.url) {
        var form = $this.parents('form');
        var url = form.attr('action');
        var data = form.serialize();
        options = $.extend({'data': data, 'url': url}, options);
    }
    App.ajax.request($this, 'POST', options);
};

$(function () {

    $('img').error(function () {
        var $this = $(this);
        var $src = $this.attr('src').replace('http://gxq.net', '');
        $src = 'http://m.gaoxquan.com' + $src;
        //$this.attr('src', $src);
    });

    $(document).on('click', '.deny-apply', function () {
        var $this = $(this);
        var href = $this.attr('id') + '&remark=';
        mui.prompt('请输入拒绝原因', '', '报名拒绝', ['确定', '取消'], function () {
            var v = arguments[0]['value'];
            if (v.length < 2) {
                mui.toast('请输入拒绝原因', {duration: 'long', type: 'div'});
                return;
            }
            href += v;
            App.ajax.get($this, {'url': href});
        }, 'div');
        document.querySelector('.mui-popup-input input').type = 'text'
    });

    $(document).on('click', '.allow-apply', function () {
        var $this = $(this);
        var href = $this.attr('id');
        App.ajax.get($this, {'url': href});
        document.querySelector('.mui-popup-input input').type = 'text'
    });

    $(document).on('click', '.del-image', function () {
        var $parent = $(this).parents('li');
        $parent.remove();
    });

    $(document).on('afterValidate', 'form', function (event, messages, errorAttributes) {
        for (var i in messages) {
            if (messages[i].length > 0) {
                mui.toast(messages[i], {duration: 'long', type: 'div'});
            }
            break;
        }
    });

    $(document).on('beforeSubmit', 'form', function () {
        var form = $(this);
        if (form.find('.has-error').length) {
            return false;
        }
        App.ajax.post(form.find(':submit'));
        return false;
    });
});

$('.send-code').on('click', function () {
    var $this = $(this);
    $this.attr('title', $this.html());

    if ($this.hasClass('disabled')) {
        return false;
    }

    var $phone = $.trim($('#user-phone').val());
    var re = /1[0-9]{10}/;
    if (!re.test($phone)) {
        mui.toast('手机号错误', {duration: 'long', type: 'div'});
        return false;
    }

    var t = 60;
    $this.addClass('disabled', 'disabled');
    $this.html(t + '秒后在获取');

    $.get($this.attr('id') + $phone, function () {
        var task = window.setInterval(function () {
            t--;
            if (t <= 0) {
                window.clearInterval(task);
                $this.removeClass('disabled').html($this.attr('title'));
                return false;
            }
            $this.html(t + '秒后在获取');
        }, 1000);
    });
    return false;
});

$(function () {
    if ($('.swiper-slide').length) {
        var swiper = new Swiper('.swiper-container', {
            pagination: '.swiper-pagination', paginationClickable: true,
            effect: 'coverflow',
            grabCursor: true,
            centeredSlides: true,
            slidesPerView: 'auto',
            loop: true,
            autoplay:3000,
            coverflow: {
                rotate: 40,
                stretch: 0,
                depth: 120,
                modifier: 1,
                slideShadows: false
            }
        });
    }

    if (typeof window['pager'] !== 'undefined') {
        App.scrollRefresh(null, window['pager']['pageCount'], window['pager']['pageUrl']);
    }
});
